# app/routes/auth.py
from flask import Blueprint, request, jsonify
from app.services.wechat_service import WechatService
from app.models.user import User
from flask_jwt_extended import create_access_token
from bson import ObjectId
import json

# 定义auth蓝图，指定url_prefix为/api/auth
auth_bp = Blueprint('auth', __name__, url_prefix='/api/auth')

@auth_bp.route('/wxlogin', methods=['POST'])
def wxlogin():
    """微信小程序登录接口：接收code和用户信息，换取openid并生成token"""

    try:
        data = request.get_json()
        if not data or "code" not in data:
            return jsonify({"code": -1, "msg": "缺少code参数"}), 400
        
        # 调用微信接口获取openid和session_key
        wechat_res = WechatService.code2session(data["code"])
        
        # 检查配置错误
        if wechat_res.get("errcode") == -2:
            return jsonify({
                "code": -1, 
                "msg": wechat_res["errmsg"]
            }), 500
            
        # 检查微信接口返回的错误
        if "errcode" in wechat_res and wechat_res["errcode"] != 0:
            return jsonify({
                "code": -1, 
                "msg": f"微信登录失败：{wechat_res['errmsg']}"
            }), 400
        
        openid = wechat_res.get("openid")
        if not openid:
            return jsonify({"code": -1, "msg": "获取openid失败"}), 500
        
        # 获取用户信息
        user_info = data.get('userInfo', {})
        
        # 创建或更新用户，同时传入用户信息
        user_id = User.create_or_update(openid, user_info)
        
        # 获取完整用户信息
        user_data = User.get_by_openid(openid)
        if not user_data:
            return jsonify({"code": -1, "msg": "用户信息获取失败"}), 500
        
        # 转换ObjectId为字符串
        user_data["_id"] = str(user_data["_id"])
        
        # 生成JWT token
        token = create_access_token(identity=str(user_id))
        
        # 返回登录结果，包含完整用户信息
        return jsonify({
            "code": 0,
            "msg": "微信登录成功",
            "data": {
                "user_id": str(user_id),
                "openid": openid,
                "token": token,
                "nickname": user_data.get("nickname", ""),
                "avatar_url": user_data.get("avatar_url", ""),
                "gender": user_data.get("gender", 0),
                "country": user_data.get("country", ""),
                "province": user_data.get("province", ""),
                "city": user_data.get("city", "")
            }
        })
        
    except Exception as e:
        # 记录详细的错误信息
        import traceback
        traceback.print_exc()
        return jsonify({
            "code": -1,
            "msg": f"服务器内部错误: {str(e)}"
        }), 500